package xyz.xtgl.config;

import common.core.util.CommonUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import xyz.xtgl.oahth2.config.constant.GlobalConstant;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liubo
 * @created 2020-02-15 13:39
 */
@Slf4j
@Configuration
public class FeignConfig {
    /**
     * feign 传递个给 下一个服务的公共参数
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                if(CommonUtil.isNotEmpty(RequestContextHolder.getRequestAttributes())){
                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                    if(CommonUtil.isNotEmpty(request.getHeader(GlobalConstant.AUTHORIZATION_HEADER_KEY))){
                        template.header(GlobalConstant.AUTHORIZATION_HEADER_KEY,  request.getHeader(GlobalConstant.AUTHORIZATION_HEADER_KEY));
                    }
                }
            }
        };
    }
}
